import { NextResponse } from 'next/server'
import { API, API_PREFIX, SERVER_BASE } from "@/config";

export const config = {
  matcher: [`/landing`, `/map`, `/game`, `/wheel`, `/rank`, `/price`],
}

export async function middleware(request, event) {
  let resolve = await isAuthValid(request);
  if (resolve) return NextResponse.next();

  const authUrl = new URL('/', request.url)
  return NextResponse.redirect(authUrl)
}

/**
 * 校验
 * @param request
 * @returns {Promise<null|*>}
 */
async function isAuthValid(request) {
  const token = request.cookies.get('csrf_access_token');
  console.log(token)
  if (!token) return null;

  let resp = await fetch(`/${API_PREFIX}/${API.user.userinfo}`, {
    headers: {Authorization: `Bearer ${token}`}
  });
  resp = await resp.json();
  if (resp?.error_code === 0 && resp?.msg === `ok`) return resp.data;

  return null
}
